import dayjs from 'dayjs'
// import * as io from '@/services/socket_io/uni-socket.io.js'
// import io from '@hyoga/uni-socket.io';
import HTMLParser from '@/utils/html-parser'
// import websocketUtil from '@/services/socket_io/index.js'

// import { useAppStoreWithOut } from '@/stores/modules/app'

const globalData = {
  domain: 'https://weapp.miyingbl.com/',
  domainOss: 'https://ossresource.miyingbl.com/',
  wss: 'wss://weapp.miyingbl.com/socket.io/?EIO=4&transport=websocket',
  imagePrefix: 'https://ossresource.miyingbl.com/static/weapp/pz/',
  api_server: '/api/',
  slogn: '咪婴陪诊',
  platform: 'pz',
  socketOpen: false,
  socketLoginStatus: false,
  socket: null,
  socketConnectNum: 0,
}

function dealMessageInfoFormat(str: string) {
  console.log('str', str)
  const regex = /{(.*)}/
  const matches = str.match(regex)

  console.log('matches', matches)
  if (matches && matches.length > 1) {
    const jsonString = matches[0] // 获取大括号内的内容
    const json = JSON.parse(jsonString) // 将内容解析为对象
    // console.log(json)

    const numberBeforeBraces = str.slice(0, matches.index) // 获取大括号前的数字
    console.log(numberBeforeBraces)

    return {
      numberBeforeBraces,
      json,
    }
  }
}

export default function () {
  const jumpToOtherApp = (path: string) => {
    // 是否有冒号
    if (path.includes(':')) {
      const [type, appid, pagePath] = path.split(':')
      if (type === 'miniProgram') {
        uni.navigateToMiniProgram({
          appId: appid,
          path: pagePath,
          fail: (err) => {
            console.log(err)
          },
        })
      }
    } else {
      //   本项目
      uni.navigateTo({
        url: path,
      })
    }
  }

  const makePhoneCall = (phoneNumber) => {
    return uni.makePhoneCall({
      phoneNumber,
    })
  }

  const getStatusBarHeight = () => {
    return uni.getSystemInfoSync().statusBarHeight || 0
  }

  const previewImage = (t: any, r?: any) =>
    uni.previewImage({
      urls: t,
      current: r,
    })

  const showFile = function (t: any) {
    if (!t) return
    if (t.indexOf('x-oss-process') < 0 && t.indexOf(globalData.domainOss) >= 0) {
      let r = 'android' == globalData.platform ? 'and' : 'ios'
      t = ''.concat(t, '?x-oss-process=style/').concat(r)
    }
    return t
  }

  const formatMoney = function (e: any, t: any) {
    return (
      (t = t || !1),
      e ? (t ? Number(e).toFixed(2) : parseFloat(Number(e).toFixed(2))) : t ? '0.00' : 0
    )
  }

  const formatTimes = function (e: any, t: any) {
    if (!e && !t) return ''
    const r = dayjs(e).format('YYYY-MM-DD')
    return e + ' ~ ' + t.replace(r, '')
  }

  const __map = (e: any, t: any) => {
    if (Array.isArray(e)) {
      return e.map((item, index) => t(item, index))
    } else if (typeof e === 'object') {
      return Object.keys(e).reduce((result, key, index) => {
        result[key] = t(e[key], key, index)
        return result
      }, {})
    } else if (typeof e === 'number') {
      return Array.from({ length: e }, (_, index) => t(index, index))
    }
    return []
  }

  function handleMessage(t: any) {
    if (t.code !== 40010) {
      switch (t.event) {
        case 'auth':
          globalData.socketLoginStatus = true
          break

        case 'msg_new':
          // eslint-disable-next-line no-case-declarations
          const routerList = getCurrentPages
          // eslint-disable-next-line no-case-declarations
          const curPage = routerList[routerList.length - 1]
          // eslint-disable-next-line no-case-declarations
          const a = curPage.route
          // eslint-disable-next-line no-case-declarations
          const n = a.indexOf('/pagesP/chat') >= 0
          // eslint-disable-next-line no-case-declarations
          if (n || r) {
            if (r) {
              uni.$emit('chat_msg_new', t.data)
            } else {
              uni.$emit('chat_session_new', t.data)
            }
          } else {
            // const store = useAppStoreWithOut()
            // const s = JSON.parse(JSON.stringify(store.getUserInfo))
            // s.dialog_unread = s.hasOwnProperty('dialog_unread') ? s.dialog_unread : 0
            // s.dialog_unread = s.dialog_unread + 1
            // uni.setTabBarBadge(s.dialog_unread)
            // store.setUserInfo(s)
          }
          break

        case 'no_read_message':
          // const store = useAppStoreWithOut()
          // const i = JSON.parse(JSON.stringify(store.getUserInfo))
          // i.no_read_message = t.data.no_read_message > 0 ? t.data.no_read_message : 0
          // store.setUserInfo(i)
          break

        default:
          uni.$emit(t.event, t)
      }
    } else {
      globalData.socketLoginStatus = false
    }
  }

  const getSockets = async () => {
    console.log('globalData.socket', globalData.socket)

    if (globalData.socket) {
      return globalData.socket
    }

    const socket = new websocketUtil(globalData.wss, 3000, (res: any) => {
      // console.log('message', res.data)
      let obj = {}
      if (isNaN(Number(res.data))) {
        obj = dealMessageInfoFormat(res.data)
      }
      // console.log(obj)
      globalData.socketConnectNum = obj.numberBeforeBraces
      if (obj.json && obj.json.sid) {
        socket.send(`${42}["auth",{"token":"${uni.getStorageSync('token')}"]`)
      }

      handleMessage(res)
    })
    // const socket = globalData.socket = new io(, socketOptions)

    // socket.on('connect', () => {
    //   console.log('socket连接成功')
    //   globalData.socketOpen = true
    //   const token = uni.getStorageSync('token')
    //   if (token) {
    //     socket.emit('auth', token)
    //   }
    // })
    //
    // socket.on('message', (data: any) => {
    //   handleMessage(data)
    // })
  }

  const parseHtml = (value: string) => {
    const htmlString = value.replace(/\\/g, '').replace(/<img/g, '<img style="max-width:100%;"')
    return HTMLParser(htmlString)
  }

  const onShareAppMessage = () => {
    const currentPage = getCurrentPages()[getCurrentPages().length - 1]
    const route = `/${currentPage.route}`
    let options = JSON.parse(JSON.stringify(currentPage.options))
    const extShareParam = currentPage.__data__.extShareParam

    if (extShareParam) {
      options = { ...options, ...extShareParam }
    }

    // options.share_uuid = this.$shareLog("onShareAppMessage", route, JSON.stringify(options));
    let shareUrl = currentPage.__data__.shareUrl
    let shareImage = currentPage.__data__.shareImage

    if (shareUrl) {
      const urlParts = shareUrl.split('?')
      if (urlParts.length > 0) {
        route = urlParts[0]
        if (urlParts.length > 1) {
          options = { ...options, ...this.$parse(urlParts[1]) }
        }
      }
    }

    let shareTitle = currentPage.__data__.shareTitle
    // const pageInfo = this.$getPageInfo(currentPage.route);
    //
    // if (pageInfo.image) {
    //   shareImage = pageInfo.image;
    // }
    //
    // if (pageInfo.title) {
    //   shareTitle = pageInfo.title;
    // }
    //
    // if (pageInfo.param) {
    //   options = { ...options, ...this.$parse(pageInfo.param) };
    // }
    //
    // shareTitle = shareTitle.length > 30 ? shareTitle.substr(0, 30) + "..." : shareTitle;
    // if (Object.keys(options).length > 0) {
    //   route += "?" + this.$stringify(options);
    // }

    console.log(shareTitle, route, shareImage)

    return {
      title: shareTitle,
      path: route,
      imageUrl: shareImage,
    }
  }

  return {
    jumpToOtherApp,
    getStatusBarHeight,
    makePhoneCall,
    previewImage,
    formatMoney,
    showFile,
    formatTimes,
    __map,
    getSockets,
    parseHtml,
    onShareAppMessage,
  }
}
